/*
    Dropdown
    author: zhao xin
    date: 2016.9
*/


! function($) {
    'use strict';

    $.fn.dropdown = function(opt) {
        this.each(function(index, el) {
            var $trigger = $(el);
            var $dropdown = $trigger.closest('.dropdown, .dropup');
            var $menu = $dropdown.find('.dropdown-menu');
            var initialized = $trigger.data('dropdown-init'); // if dropdown is already initialized.

            if (!initialized) {
                $trigger.on('open', function(e) {
                    $menu.addClass('show');
                });
                $trigger.on('close', function(e) {
                    $menu.removeClass('show');
                });
                $trigger.on('toggle', function(e) {
                    if ($menu.hasClass('show')) {
                        $menu.removeClass('show');
                    } else {
                        $menu.addClass('show');
                    }
                });
                // trigger by hover
                if (typeof opt === 'object' && opt.hover) {
                    $dropdown.hover(function() {
                        $trigger.trigger('open');
                    }, function() {
                        $trigger.trigger('close');
                    });
                } else {
                    $menu.on('click', function(e) {
                        e.stopPropagation();
                    });
                    $(document).on('click', function(e) {
                        $trigger.trigger('close');
                    });
                }
                $trigger.on('click', function(e) {
                    $trigger.trigger('toggle');
                    e.stopPropagation();
                });
                $menu.on('click', 'a', function(e) {
                    if (!$(this).hasClass('disabled')) {
                        $trigger.trigger('close');
                        e.stopPropagation();
                    }
                });
                $trigger.data('dropdown-init', true);
            }

            if (opt === 'open') {
                $trigger.trigger('open');
            } else if (opt === 'close') {
                $trigger.trigger('close');
            }
        });
    }

    $(document).ready(function() {
        $('[data-init="dropdown"]').each(function(index, el) {
            $(el).dropdown();
        });
    });
}(jQuery);